<?php

namespace App\Command\ResumeParsing\Service\ParsingSpecial;

use App\Service\FileHandler;
use EchoPHP\Facades\Log;

class ParsingLagou extends ParsingSpecialXml {

    function __construct($helper) {
        parent::__construct($helper);

        $this->get['template'] = function () {
            $this->listXPath("//templateTag[normalize-space()='templateTagName']");    //[contains(., 'templateTagName')][starts-with(normalize-space(), 'templateTagName')]
            $result = $this->xPath->query();
            if ($result->length < 1) return '';
            return $this->formatTxt($result[0]->textContent);
        };

        $this->get['id'] = $this->tagNotExist;

        $this->get['time'] = $this->tagNotExist;

        $this->get['name'] = function () {
            //$this->listXPath("//div/table/tr/td[contains(., '/')]/p/b/span[@style[contains(., 'font-size:24.0pt')]][1]/text()[normalize-space()]",0);
            $result = $this->xPath->query("//div/table/tr/td[contains(., '/')]/p/b/span[@style[contains(., 'font-size:24.0pt')]][1]/text()[normalize-space()]");
            if ($result->length < 1) return '';
            return $this->formatTxt($result[0]->textContent);
        };

        $this->groupGetter['basic'] = array();

        $this->groupGetter['basic'][0] = function () {
            //$this->listXPath("//div/table/tr/td[contains(., '/') and p/b/span[@style[contains(., 'font-size:24.0pt')]]][1]/p[3]");
            $result = $this->xPath->query("//div/table/tr/td[contains(., '/') and p/b/span[@style[contains(., 'font-size:24.0pt')]]][1]/p[3]");
            if ($result->length < 1) return '';
            return preg_split('/\s+\/\s+/u', $this->formatTxt($result[0]->textContent, TRUE));
        };

        $this->groupGetter['basic'][] = function ($text) {
            if (preg_match('/^(?:\d{1,2}\s*年(?:\s*[01]?\d\s*个?月)?|\d{1,2}\s*个?月)(?:\s*以上|\+)?(?=工作经验)/u', $text, $matches)) {
                return array('workyear' => $matches[0]);
            }
        };

        $this->groupGetter['basic'][] = function ($text) {
            static $dictDegree = array(
                "博士后" => 9,
                "博士" => 9,
                "MBA" => 8,
                "EMBA" => 8,
                "硕士" => 7,
                "本科" => 6,
                "大专" => 5,
                "中专" => 4,
                "中技" => 3,
                "中技" => 3,
                "高中" => 2,
                "中学" => 1,
                "初中" => 1,
                "初中以下" => 1,
                "初中及以下" => 1,
                "小学" => 1
            );
            if (isset($dictDegree[$text])) return array('degree' => $text);
        };

        $this->groupGetter['basic'][] = function ($text) {
            if (preg_match('/^\d{2}岁$/u', $text)) {
                return array('age' => $text);
            }
        };

        $this->get['sex'] = function () {
            //$this->listXPath("//div/table/tr/td[contains(., '/')]/p/b/span[@style[contains(., 'font-size:24.0pt')]][1]/span/img[@width=14 and @height=14]/@src");
            $result = $this->xPath->query("//div/table/tr/td[contains(., '/')]/p/b/span[@style[contains(., 'font-size:24.0pt')]][1]/span/img[@width=14 and @height=14]/@src");
            if ($result->length < 1) {
                $result = $this->xPath->query("//div/table/tr/td[contains(., '/')]/p/b/span[@style[contains(., 'font-size:24.0pt')]][1]/span[normalize-space()='男' or normalize-space()='女']");
                if ($result->length < 1) return '';
                $text = $this->formatTxt($result[0]->textContent);
                if ($text == '女') return '女';
                if ($text == '男') return '男';
                return '';
            }
            $imgPath = $result[0]->textContent;
            if (mb_strpos($imgPath, 'woman') !== false) return '女';
            if (mb_strpos($imgPath, 'man') !== false) return '男';
            return '';
        };

        $this->get['nation'] = $this->tagNotExist;

        $this->get['identitycard'] = $this->tagNotExist;

        $this->groupGetter['contact'][0] = function () {
            //$this->listXPath("//div/table/tr/td[contains(., '/') and p/b/span[@style[contains(., 'font-size:24.0pt')]]][1]/p[5]");
            $result = $this->xPath->query("//div/table/tr/td[contains(., '/') and p/b/span[@style[contains(., 'font-size:24.0pt')]]][1]/p[5]");
            if ($result->length < 1) return '';
            return preg_split('/\r\n|[\r\n]/u', $this->formatTxt($result[0]->textContent));
        };

        $this->groupGetter['contact'][] = function ($text) {
            if (preg_match('/^1\d{10}$/', $text)) {
                return array('mobile' => $text);
            }
        };

        $this->groupGetter['contact'][] = function ($text) {
            if (preg_match('/^\S+@[\w\-]+\.\S+$/', $text)) {
                return array('email' => $text);
            }
        };

        $this->get['mobile'] = $this->groupGet('mobile', 'contact');

        $this->get['email'] = $this->groupGet('email', 'contact');

        $this->get['age'] = $this->groupGet('age', 'basic');

        $this->get['married'] = $this->tagNotExist;

        $this->get['politic'] = $this->tagNotExist;

        $this->get['degree'] = $this->groupGet('degree', 'basic');

        $this->get['industry'] = $this->tagNotExist;

        $this->get['position'] = function () {
            //$this->listXPath("//div/table/tr/td/p/span[contains(., '期望职位：')]");
            $result = $this->xPath->query("//div/table/tr/td/p/span[contains(., '期望职位：')]");
            if ($result->length < 1) return '';
            return $this->preg_get('/(?:期望职位：)\s*(?<result>.*?)\s*(?=\/|$)/u', $result[0]->textContent, array('groupName' => 'result'));
        };

        $this->get['career'] = $this->tagNotExist;

        $this->get['major'] = $this->tagNotExist;

        $this->get['birthday'] = $this->tagNotExist;

        $this->get['workyear'] = $this->groupGet('workyear', 'basic');

        $this->get['workarea'] = $this->tagNotExist;

        $this->get['expectarea'] = $this->tagNotExist;

        $this->get['area'] = $this->tagNotExist;

        $this->get['salary'] = $this->tagNotExist;

        $this->get['expectsalary'] = function () {
            //$this->listXPath("//div/table/tr/td/p/span[contains(., '期望薪资：')]");
            $result = $this->xPath->query("//div/table/tr/td/p/span[contains(., '期望薪资：')]");
            if ($result->length < 1) return '';
            $resultText = $this->preg_get('/(?:期望薪资：)\s*(?<result>.*?)\s*(?=\/|$)/u', $result[0]->textContent, array('groupName' => 'result'));
            $expectsalary = $this->func->parseSalary($resultText);
            if (count($expectsalary)) {
                $this->helper->resumeInfo['expectsalaryfrom'] = $expectsalary['monthly']['begin'];
                $this->helper->resumeInfo['expectsalaryend'] = $expectsalary['monthly']['end'];
                //$this->helper->resumeInfo['expectsalaryafrom'] = $expectsalary['annual']['begin'];
                //$this->helper->resumeInfo['expectsalaryaend'] = $expectsalary['annual']['end'];
            }
            return $resultText;
        };

        $this->get['jobterm'] = $this->tagNotExist;

        $this->get['school'] = $this->tagNotExist;

        $this->get['nofocuse'] = $this->tagNotExist;

        $this->get['workinfo'] = function () {
            //$this->listXPath("//p[normalize-space()='工作经历']/following-sibling::*[self::p or self::table]");
            $result = $this->xPath->query("//p[normalize-space()='工作经历']/following-sibling::*[self::p or self::table]");
            if ($result->length < 1) return array();
            $data = array();
            foreach ($result as $node) {
                if (in_array($this->formatTxt($node->textContent, TRUE), array('项目经验', '教育经历'))) break;
                if ($node->localName == 'table') {
                    if (isset($item)) {
                        $item['comment'] = trim($item['comment']);
                        $data[] = $item;
                    }
                    $company = preg_split('/\s*\/\s*/u', $this->formatTxt($this->xPath->query("tr[1]/td[2]", $node)[0]->textContent, TRUE));
                    $time = $this->formatTxt($this->xPath->query("tr[1]/td[3]", $node)[0]->textContent, TRUE);
                    $tmp = $this->func->parseTimespan($time);
                    $duty = $this->formatTxt($this->xPath->query("tr[2]/td[1]", $node)[0]->textContent, TRUE);
                    $item = array(
                        'comment' => !empty($company[1]) ? $company[1] : '',
                        'time' => $time, 'time_from' => $tmp['begin'], 'time_end' => $tmp['end'],
                        'company' => $company[0],
                        'duty' => $duty,
                    );
                } elseif (isset($item)) {
                    if ($node->attributes && ($style = $node->attributes->getNamedItem('style')) && strpos($style->value, 'line-height:150%') !== FALSE) {
                        $item['comment'] .= "\r\n" . $this->formatTxt($node->textContent, 'space');
                    } elseif ($node->attributes && ($style = $node->attributes->getNamedItem('style')) && strpos($style->value, 'line-height:115%') !== FALSE) {
                        $item['comment'] .= "\r\n" . $this->recoverText($node->textContent);
                    }
                }
            }
            $item['comment'] = trim($item['comment']);
            $data[] = $item;
            return $data;
        };

        $this->get['projectinfo'] = function () {
            //$this->listXPath("//p[normalize-space()='项目经验']/following-sibling::*[self::p or self::table]");
            $result = $this->xPath->query("//p[normalize-space()='项目经验']/following-sibling::*[self::p or self::table]");
            if ($result->length < 1) return array();
            $data = array();
            foreach ($result as $node) {
                if (in_array($this->formatTxt($node->textContent, TRUE), array('教育经历'))) break;
                if ($node->localName == 'table') {
                    if (isset($item)) {
                        $item['comment'] = trim($item['comment']);
                        $data[] = $item;
                    }
                    $project = $this->formatTxt($this->xPath->query("tr/td[1]", $node)[0]->textContent, TRUE);
                    $company = '';
                    if (preg_match('/^(?<project>.*?)(?:\s*\((?<company>.*)\))?$/u', $project, $matches)) {
                        $project = $matches['project'];
                        if (!empty($matches['company'])) $company = $matches['company'];
                    }
                    $time = $this->formatTxt($this->xPath->query("tr/td[2]", $node)[0]->textContent, TRUE);
                    $tmp = $this->func->parseTimespan($time);
                    $item = array(
                        'comment' => '',
                        'time' => $time, 'time_from' => $tmp['begin'], 'time_end' => $tmp['end'],
                        'project' => $project,
                        'company' => $company,
                    );
                } elseif (isset($item) && $node->attributes && ($style = $node->attributes->getNamedItem('style')) && strpos($style->value, 'line-height:115%') !== FALSE) {
                    $item['comment'] .= "\r\n" . $this->recoverText($node->textContent);
                }
            }
            $item['comment'] = trim($item['comment']);
            $data[] = $item;
            return $data;
        };

        $this->get['educationinfo'] = function () {
            //$this->listXPath("//p[normalize-space()='教育经历']/following-sibling::table");
            $result = $this->xPath->query("//p[normalize-space()='教育经历']/following-sibling::table");
            if ($result->length < 1) return array();
            $data = array();
            foreach ($result as $table) {
                if (isset($item)) $data[] = $item;
                $school = $this->formatTxt($this->xPath->query("tr[1]/td[2]", $table)[0]->textContent, TRUE);
                $time = $this->formatTxt($this->xPath->query("tr[1]/td[3]", $table)[0]->textContent, TRUE);
                $tmp = $this->func->parseTimespan($time, TRUE);
                $degree = preg_split('/\s*\/\s*/u', $this->formatTxt($this->xPath->query("tr[2]/td[1]", $table)[0]->textContent, TRUE));
                $item = array(
                    'comment' => '',
                    'time' => $time, 'time_from' => $tmp['begin'], 'time_end' => $tmp['end'],
                    'school' => $school,
                    'degree' => $degree[0],
                    'major' => !empty($degree[1]) ? $degree[1] : ''
                );
            }
            $data[] = $item;
            return $data;
        };

        $this->get['skillinfo'] = $this->tagNotExist;

        $this->get['awardinfo'] = $this->tagNotExist;

        $this->get['commentinfo'] = function () {
            //$this->listXPath("//p[normalize-space()='自我描述']/following-sibling::p");
            $result = $this->xPath->query("//p[normalize-space()='自我描述']/following-sibling::p");
            if ($result->length < 1) return '';
            if ($result->length < 2 || empty($result[1]->attributes) || empty($result[1]->attributes->getNamedItem('style'))) {
                return $this->recoverText($result[0]->textContent);
            }
            return $this->formatTxt($result[0]->textContent, 'space') . "\r\n" . $this->recoverText($result[1]->textContent);
        };

        $this->get['otherinfo'] = function () {
            //$this->listXPath("//div/table/tr/td[contains(., '/') and p/b/span[@style[contains(., 'font-size:24.0pt')]]][1]/p[2]");
            $result = $this->xPath->query("//div/table/tr/td[contains(., '/') and p/b/span[@style[contains(., 'font-size:24.0pt')]]][1]/p[2]");
            $resultText = $this->groupCache['comment'];
            $resultText .= "\r\n" . $this->formatTxt($result[0]->textContent, TRUE);
            return trim($resultText);
        };

        $this->get['avatar'] = function () {
            try {
                //$this->listXPath("//div/table/tr/td[contains(., '/') and p/b/span[@style[contains(., 'font-size:24.0pt')]]][1]/preceding-sibling::td[1]/p/img[1]/@src");
                $result = $this->xPath->query("//div/table/tr/td[contains(., '/') and p/b/span[@style[contains(., 'font-size:24.0pt')]]][1]/preceding-sibling::td[1]/p/img[1]/@src");
                if (!count($result) || empty($internalPath = $result[0]->textContent) || preg_match('/\/default.*?headpic3\.png$/i', $internalPath)) return '';
                if (empty($this->helper->resume['resumeImage']) || empty($this->helper->resume['resumeImage'][$internalPath])) return '';

                return ['data' => &$this->helper->resume['resumeImage'][$internalPath]['data'], 'name' => basename($internalPath)];
            } catch (\Exception $e) {
                Log::error(e_dump($e), ['avatar' => $internalPath ?? ''], 'cmd');
                return '';
            }
        };
    }
}